package com.xjtu.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.springframework.stereotype.Component;


/**
 * 监测channel心跳
 */
@Component
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                //System.out.println("进入读空闲......");
            } else if (event.state() == IdleState.WRITER_IDLE) {
                //System.out.println("进入写空闲......");
            } else if (event.state() == IdleState.ALL_IDLE) {
                Channel channel = ctx.channel();
                String msg = "{ \"type\": \"ping\" }";
                channel.writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }
}
